#include "bsp_adc.h"
#include "math.h"    //数学公式

void bsp_adc_init(MYADC1_Typedef *UserADC1, MYADC2_Typedef *UserADC2)
{
    HAL_GPIO_WritePin(GPIOB, GPIO_PIN_7, GPIO_PIN_SET);

    HAL_ADCEx_Calibration_Start(&hadc1, ADC_SINGLE_ENDED);
    HAL_ADC_Start_DMA(&hadc1,(uint32_t*)&UserADC1->ADC_Value,6);

    HAL_ADCEx_Calibration_Start(&hadc2, ADC_SINGLE_ENDED);
    HAL_ADC_Start_DMA(&hadc2,(uint32_t*)&UserADC2->ADC_Value,6);

	//关闭DMA传输完成中断
	HAL_NVIC_DisableIRQ(DMA1_Channel1_IRQn);
	HAL_NVIC_DisableIRQ(DMA1_Channel2_IRQn);
}

void bsp_adc1_read(MYADC1_Typedef *UserADC1)
{
    UserADC1->ADC_Channel.IBUS_f = (((float)UserADC1->ADC_Channel.IBUS - 2048) * (3.3f / 4095.0f)) / (0.001f * 20.0f);
//    UserADC1->ADC_Channel.IA_f = (((float)UserADC1->ADC_Channel.IA - 2048) * (3.3f / 4095.0f)) / (0.001f * 20.0f);
//    UserADC1->ADC_Channel.IB_f = (((float)UserADC1->ADC_Channel.IB - 2048) * (3.3f / 4095.0f)) / (0.001f * 20.0f);
//    UserADC1->ADC_Channel.IC_f = (((float)UserADC1->ADC_Channel.IC - 2048) * (3.3f / 4095.0f)) / (0.001f * 20.0f);
    
	float Temp1;         //温度值
	float R = 10000;    //热敏电阻NTC103
	float B = 3428;     //NTC固有参数
	float T2= (273.15f+25.0f);

	float V_NTC1 = (float)UserADC1->ADC_Channel.NTC1 * (3.3f / 4095.0f);//测得实际电压值
	float Rt1 = V_NTC1 * 10000.0f / (3.3f - V_NTC1);			//推测得到的电阻值
	Temp1 = 1.0f/(logf(Rt1/R)/B+1/T2);		//温度计算
	UserADC1->ADC_Channel.NTC1_f = Temp1 - 273.15f;        //最终的温度值

    UserADC1->ADC_Channel.NTC3_f = (float)UserADC1->ADC_Channel.NTC3 - 2048.0f;
}

void bsp_adc2_read(MYADC2_Typedef *UserADC2)
{
    UserADC2->ADC_Channel.VBUS_f = (float)UserADC2->ADC_Channel.VBUS * (3.3f / 4095.0f) * 16.0f;
    UserADC2->ADC_Channel.VA_f = (float)UserADC2->ADC_Channel.VA * (3.3f / 4095.0f) * 16.0f;
    UserADC2->ADC_Channel.VB_f = (float)UserADC2->ADC_Channel.VB * (3.3f / 4095.0f) * 16.0f;
    UserADC2->ADC_Channel.VC_f = (float)UserADC2->ADC_Channel.VC * (3.3f / 4095.0f) * 16.0f;
    
	float Temp2;         //温度值
	float R = 10000;    //热敏电阻NTC103
	float B = 3428;     //NTC固有参数
	float T2= (273.15f+25.0f);

	
	float V_NTC2 = (float)UserADC2->ADC_Channel.NTC2 * (3.3f / 4095.0f);//测得实际电压值
	float Rt2 = V_NTC2 * 10000.0f / (3.3f - V_NTC2);			//推测得到的电阻值
	Temp2 = 1.0f/(logf(Rt2/R)/B+1/T2);		//温度计算
	UserADC2->ADC_Channel.NTC2_f = Temp2 - 273.15f;        //最终的温度值
}
